package tech.blueglacier.codec;

import org.mozilla.universalchardet.UniversalDetector;
import tech.blueglacier.exception.UndeterminedEncodingException;

import java.io.UnsupportedEncodingException;
import java.util.Optional;

/**
 * @author zhangxinchen
 * @since 2020/7/18
 */
public class CharsetDetector {

    public static String autoDetectEncodingWithDefaultIfAbsent(byte[] bytes) {
        try {
            return autoDetectEncoding(bytes);
        } catch (UnsupportedEncodingException | UndeterminedEncodingException e) {
            return new String(bytes);
        }
    }

    public static String autoDetectEncoding(byte[] bytes)
            throws UnsupportedEncodingException, UndeterminedEncodingException {
        Optional<String> encoding = charsetAutoDetected(bytes);
        if (encoding.isPresent()) {
            return new String(bytes, encoding.get());
        }

        throw new UndeterminedEncodingException("the detector couldn't determine what encoding was used");
    }

    public static Optional<String> charsetAutoDetected(byte[] bytes) {
        UniversalDetector detector = new UniversalDetector();
        detector.handleData(bytes, 0, bytes.length);
        detector.dataEnd();
        Optional<String> encoding = Optional.ofNullable(detector.getDetectedCharset());
        detector.reset();

        return encoding;
    }
}
